<?php

include '../dbconnect.php';

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

// 生成唯一的 REVIEWS_ID
function generateReviewId($conn) {
    // 获取当前最大的 REVIEWS_ID
    $sql = "SELECT REVIEWS_ID FROM reviews ORDER BY REVIEWS_ID DESC LIMIT 1";
    $result = $conn->query($sql);
    $row = $result->fetch_assoc();
    $max_id = $row['REVIEWS_ID'];
	print_r($max_id);

    if ($max_id === null) {
        $next_id = 1;
    } else {
        $last_number = intval(substr($max_id, 9)); // 假设前缀是 "Reviews_"
        if ($last_number === 0) {
            $next_id = 1; // 处理无效的 max_id 值
        } else {
            $next_id = $last_number + 1;
        }
    }

    return "Reviews_" . str_pad($next_id, 3, '0', STR_PAD_LEFT);
}
$review_id = generateReviewId($conn);


// // 插入数据到数据库
$sql = "INSERT INTO reviews (REVIEWS_ID, REVIEWS_NAME, REVIEWS_EMAIL, REVIEWS_DESC) VALUES (?, ?, ?, ?)";

$stmt = $conn->prepare($sql);
$stmt->bind_param("ssss", $review_id, $name, $email, $message);

if ($stmt->execute()) {
    echo "Message submitted successfully!";
    // 提交成功，显示提示信息并重定向
    echo '<script type="text/javascript">';
    echo 'alert("Message submitted successfully!");';
    echo 'window.location.href = "5_reviews.php";'; // 重定向到主页或其他页面
    echo '</script>';
} else {
    echo "Error: " . $stmt->error;
}

$stmt->close();
$conn->close();
?>